<template>
  <el-dialog
    class="device-add-special-comp"
    title="设置特殊设备"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(900)"
    :before-close="handleCancel">
    <el-form
      element-loading-custom-class="custom-load"
      :model="ruleForm"
      :rules="rules"
      label-suffix="："
      ref="ruleForm"
      :label-width="$setRem(140)"
      class="rule-form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="deviceName" required>
            <span class="detail-text" v-if="hasDetail || hasMaintain || hasQuit">
              {{ ruleForm.deviceName || '' }}
            </span>
            <el-input v-else type="text" clearable placeholder="请输入设备名称" v-model="ruleForm.deviceName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号" prop="deviceModel" required>
            <span class="detail-text" v-if="hasDetail || hasMaintain || hasQuit">
              {{ ruleForm.deviceModel || '' }}
            </span>
            <el-input v-else type="text" placeholder="请输入设备型号" clearable v-model="ruleForm.deviceModel"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备编号" prop="deviceNo" required>
            <span class="detail-text" v-if="hasDetail || hasMaintain || hasQuit">
              {{ ruleForm.deviceNo || '' }}
            </span>
            <el-input v-else type="text" clearable placeholder="请输入设备编号" v-model="ruleForm.deviceNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="进场时间" prop="marchDate" required>
            <span class="detail-text" v-if="hasDetail || hasMaintain || hasQuit">
              {{ ruleForm.marchDate || '' }}
            </span>
            <el-date-picker
              v-else
              v-model="ruleForm.marchDate"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择进场时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="安装时间" prop="installDate" required>
            <span class="detail-text" v-if="hasDetail || hasMaintain || hasQuit">
              {{ ruleForm.installDate || '' }}
            </span>
            <el-date-picker
              v-else
              v-model="ruleForm.installDate"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择安装时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="操作人员" prop="operatorsId" required>
            <span class="detail-text" v-if="hasDetail || hasMaintain || hasQuit">
              {{ ruleForm.operatorsName || '' }}
            </span>
            <el-select
              v-else
              filterable
              remote
              v-model="ruleForm.operatorsId"
              placeholder="请输入姓名或身份证号进行搜索"
              :remote-method="remoteMethod"
              :loading="loading">
              <el-option
                v-for="item in currentList"
                :key="item.idNumber"
                :label="item.name"
                :value="item.idNumber">
                {{item.name}} {{item.job ? `(${item.job})` : ''}}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2" style="line-height: 3em; padding-left: 20px">
          <el-button v-show="ruleForm.operatorsId" size="small" type="primary" @click="dialogShow = true">查看证书</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="维护人员" prop="maintainersId" required>
            <span class="detail-text" v-if="hasDetail || hasMaintain || hasQuit">
              {{ ruleForm.maintainersName || '' }}
            </span>
            <el-select
              v-else
              placeholder="请选择维护人员"
              clearable
              filterable
              v-model="ruleForm.maintainersId">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最近维护时间" prop="latelyMaintainDate" required>
            <span class="detail-text" v-if="hasDetail">
              {{ ruleForm.latelyMaintainDate || '' }}
            </span>
            <el-date-picker
              v-else
              v-model="ruleForm.latelyMaintainDate"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择安装时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="维护周期" prop="maintainCycle" required>
            <span class="detail-text" v-if="hasDetail || hasMaintain || hasQuit">
              {{ ruleForm.maintainCycle || 0 }}
            </span>
            <el-input-number v-else :min="0" :controls="false" type="text" clearable placeholder="请输入维护周期（天）" v-model="ruleForm.maintainCycle"></el-input-number> &nbsp;天
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!hasMaintain">
        <el-col :span="12">
          <el-form-item label="检测报告" prop="inspectionImagesUrl" required>
            <div class="detail-text" v-if="hasDetail || hasMaintain || hasQuit">
              <template v-if="inspection">
                <el-image
                  v-if="inspection.hasImg"
                  class="img"
                  :src="inspection.url"
                  :preview-src-list="[inspection.url]">
                </el-image>
                <span v-else class="file-name" @click="fileDownload(inspection)">{{ inspection.name }}</span>
              </template>
            </div>
            <el-upload
              v-else
              class="upload-qualifications"
              ref="upload"
              action="#"
              :on-change="handleDownLoad"
              :on-remove="handleRemove"
              :on-preview="handleFileClick"
              :file-list="ruleForm.inspectionImagesUrl"
              :auto-upload="false">
              <el-button slot="trigger" :loading="uploadLoading" size="small" type="primary">选取文件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="hasMaintain || (hasDetail && ruleForm.maintainImagesUrl.length)">
        <el-col :span="12">
          <el-form-item label="维护照片" prop="maintainImagesUrl" required>
            <template v-if="hasDetail">
              <el-image
                v-for="item in ruleForm.maintainImagesUrl"
                :key="item.url"
                class="img"
                :src="$checkUrl(item.url)"
                :preview-src-list="[$checkUrl(item.url)]">
              </el-image>
            </template>
            <template v-else>
              <div
                class="img-content"
                v-show="ruleForm.maintainImagesUrl.length"
                v-for="item in ruleForm.maintainImagesUrl"
                :key="item.url">
                <el-image
                  class="img"
                  :src="$checkUrl(item.url)"
                  :preview-src-list="[$checkUrl(item.url)]">
                </el-image>
                <i
                  class="el-icon-circle-close"
                  @click.stop="handleAvatarRemove(item.url)"></i>
              </div>
              <el-upload
                v-show="!ruleForm.maintainImagesUrl.length"
                class="avatar-uploader"
                action="#"
                :limit="1"
                accept=".jpg,.png,.jpeg"
                :show-file-list="false"
                :auto-upload="false"
                :file-list="ruleForm.maintainImagesUrl"
                :on-change="beforeAvatarUpload">
                <span v-if="picLoading"  class="loading-container">
                  <i class="el-icon-loading avatar-loading-icon"></i>
                </span>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="(hasDetail && ruleForm.exitDate) || hasQuit">
        <el-col :span="12">
          <el-form-item label="退场时间" prop="exitDate" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.exitDate || '' }}</span>
            <el-date-picker
              v-else
              v-model="ruleForm.exitDate"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择退场时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="抄送人" prop="sendUserId" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.sendUserName || '' }}</span>
            <el-select
              v-else
              placeholder="请选择抄送人"
              clearable
              filterable
              v-model="ruleForm.sendUserId">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button
        size="medium"
        type="primary"
        v-if="!hasDetail"
        :loading="btnLaoding"
        @click="hanldeSubmit('1')">
        提 交
      </el-button>
      <el-button
        size="medium"
        type="primary"
        v-if="hasEdit || hasAdd"
        :loading="btnLaoding"
        @click="hanldeSubmit('0')">
        暂 存
      </el-button>
      <el-button size="medium" @click="handleCancel">取 消</el-button>
    </span>
    <certificate-detail
      :visible="dialogShow"
      :option="currentItem"
      @cancel="dialogShow = false">
    </certificate-detail>
  </el-dialog>
</template>

<script>
import certificateDetail from '@/components/project/device/certificateDetail';
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    },
    options: {
      type: Object,
      default: () => ({})
    },
    btnLaoding: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogShow: false,
      ruleForm: {
        id: '',
        deviceName: '',
        deviceModel: '',
        deviceNo: '',
        marchDate: '',
        installDate: '',
        operatorsId: '',
        operatorsName: '',
        maintainersName: '',
        maintainersId: '',
        latelyMaintainDate: '',
        maintainCycle: '',
        sendUserId: '',
        sendUserName: '',
        inspectionImagesUrl: [],
        maintainImagesUrl: [],
        deviceType: '1',
        exitDate: ''
      },
      rules: {
        deviceName: [
          { required: true, message: '请输入设备名称' },
        ],
        deviceModel: [
          { required: true, message: '请输入设备型号' },
        ],
        deviceNo: [
          { required: true, message: '请输入设备编号' },
        ],
        marchDate: [
          { required: true, message: '请选择进场时间' },
        ],
        installDate: [
          { required: true, message: '请选择安装时间' },
        ],
        operatorsId: [
          { required: true, message: '请选择操作人员' },
        ],
        maintainersId: [
          { required: true, message: '请选择维护人员' },
        ],
        latelyMaintainDate: [
          { required: true, message: '最近维护时间' },
        ],
        maintainCycle: [
          { required: true, message: '请输入维护周期' },
        ],
        inspectionImagesUrl: [
          { type: 'array', required: true, message: '请上传检测报告' }
        ],
        maintainImagesUrl : [
          { type: 'array', required: true, message: '请上传维护照片' }
        ],
        sendUserId: [
          { required: true, message: '请选择抄送人' },
        ],
        exitDate: [
          { required: true, message: '请选择退场时间' },
        ]
      },
      // 维护人员
      maintainersList: [],
      searchList: [],
      userList: [],
      loading: false,
      uploadLoading: false,
      picLoading: false
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userInfo() {
      return this.$store.state.userInfo;
    },
    // 当前操作人员列表
    currentList() {
      return this.searchList.length
        ? this.searchList
        : this.maintainersList;
    },
    // 当前选择的操作人员信息
    currentItem() {
      return this.currentList.find(v => v.idNumber === this.ruleForm.operatorsId) || {};
    },
    // 检测报告
    inspection() {
      const { inspectionImagesUrl } = this.ruleForm;
      if (Array.isArray(inspectionImagesUrl)) {
        const files = inspectionImagesUrl[0] || {};
        return {
          ...files,
          url: this.$checkUrl(files.url),
          hasImg: /\.jpg|\.jpeg|\.png$/.test(files.url)
        };
      }
      return null;
    },
    hasDetail() {
      return this.type === 'detail';
    },
    // 维护
    hasMaintain() {
      return this.type === 'maintain';
    },
    hasAdd() {
      return this.type === 'add';
    },
    hasEdit() {
      return this.type === 'edit';
    },
    // 退场
    hasQuit() {
      return this.type === 'quit';
    }
  },
  watch: {
    options: {
      deep: true,
      handler(data) {
        if (data) {
          Object.keys(this.ruleForm).forEach(key => {
            const value = data[key] || '';
            if (key === 'deviceType') {
              this.ruleForm[key] = value || '1';
              return;
            }
            if (key === 'maintainCycle') {
              this.ruleForm[key] = value || 0;
              return;
            }
            if (key === 'exitDate') {
              this.ruleForm[key] = value || this.$moment().format('YYYY-MM-DD');
              return;
            }
            if (key === 'inspectionImagesUrl' || key === 'maintainImagesUrl') {
              const fileNames = value ? value.match(/([^\/])+\.\w+$/) : '';
              const fileName = Array.isArray(fileNames) ? fileNames[0] : '';
              if (value) this.ruleForm[key] = [{
                name: fileName,
                url: value
              }];
              return;
            }
            this.ruleForm[key] = value;
          });
        }
      }
    },
    visible(val) {
      if (!val) {
        this.ruleForm = {
          id: '',
          deviceName: '',
          deviceModel: '',
          deviceNo: '',
          marchDate: '',
          installDate: '',
          operatorsId: '',
          operatorsName: '',
          maintainersName: '',
          maintainersId: '',
          latelyMaintainDate: '',
          maintainCycle: '',
          sendUserId: '',
          sendUserName: '',
          inspectionImagesUrl: [],
          maintainImagesUrl: [],
          deviceType: '1',
          exitDate: ''
        };
        this.uploadLoading = false;
        this.picLoading = false;
      }
    }
  },
  created() {
    this.getSpecialUsers();
    this.getUserList();
  },
  components: {
    certificateDetail
  },
  methods: {
    /**
     * 获取用户列表数据
     */
    async getUserList() {
      const params = {
        pageFlag: false
      };
      const { success, data: {
        data
      }} = await this.$Model.getUserList(params);
      if (success && data) {
        this.userList = data.list || [];
      }
    },
    /**
     * 获取人员列表所有数据
     */
    async getSpecialUsers() {
      const params = {
        project_id: this.projectId,
        classification: '特种人员',
        page: '1',
        limit: '100'
      };
      const { success, data } = await this.$Model.getAllWorkersInfo(params);
      if (success && data.data) {
        const { workers_info = [] } = data.data;
        this.maintainersList = workers_info;
      }
    },
    // 搜索维护人员
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(async () => {
          const { success, data } = await this.$Model.getWorkersInfoBySearch({
            project_id: this.projectId,
            classification: '特种人员',
            page: '1',
            limit: '100',
            key: query
          });
          this.loading = false;
          if (success && data.data) {
            const { workers_info = [] } = data.data;
            this.searchList = workers_info;
          }
        }, 200);
        return;
      }
      this.searchList = [];
    },
    fileDownload(data) {
      window.open(data.url);
    },
    /**
     * 选取文件
     * @param file {File} 当前文件
     * @param fileList {FileList} 文件列表
     */
    handleDownLoad(file, fileList) {
      // this.ruleForm.inspectionImagesUrl = [file.raw];
      this.fileUpload(file.raw);
      return false;
    },
    // 上传文件
    async fileUpload(file) {
      const fm = new FormData();
      fm.append('file', file);
      this.uploadLoading = true;
      const { success, data: { data }} = await this.$Model.fileUpload(fm);
      this.uploadLoading = false;
      if (success && data) {
        this.ruleForm.inspectionImagesUrl = [{
          name: file.name,
          url: data
        }];
        this.$refs.ruleForm.validateField('inspectionImagesUrl');
      }
    },
    /**
     * 删除文件
     * @param file {File} 当前文件
     * @param fileList {FileList} 文件列表
     */
    async handleRemove(file, fileList) {
      // await this.$Model.fileDelete({ filePath: file.url });
      this.ruleForm.inspectionImagesUrl = [];
    },
    /**
     * 点击文件列表中已上传的文件时的钩子
     * @param file {File} 当前文件
     */
    handleFileClick(file) {
      if (file.url) window.open(this.$checkUrl(file.url));
    },
    // 上传图片
    async beforeAvatarUpload(file) {
      const fm = new FormData();
      fm.append('file', file.raw);
      this.picLoading = true;
      const { success, data: { data }} = await this.$Model.fileUpload(fm);
      this.picLoading = false;
      if (success) {
        this.ruleForm.maintainImagesUrl = [{
          name: file.name,
          url: data
        }];
        this.$refs.ruleForm.validateField('maintainImagesUrl');
      }
    },
    // 删除照片
    async handleAvatarRemove(url) {
      // await this.$Model.fileDelete({ filePath: url });
      this.ruleForm.maintainImagesUrl = [];
    },
    handleCancel() {
      this.$emit('cancel');
    },
    async hanldeSubmit(type) {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const {
            inspectionImagesUrl,
            maintainImagesUrl,
            exitDate
          } = this.ruleForm;
          const params = {
            ...this.ruleForm,
            projectId: this.projectId,
            operatorsName: this.currentItem.name || '',
            inspectionImagesUrl: inspectionImagesUrl[0]
              ? inspectionImagesUrl[0].url
              : '',
            createId: this.userInfo.uuid,
            cacheFlag: type // 0：暂存；1：发送
          };
          delete params.maintainImagesUrl;
          delete params.exitDate;
          if (this.hasMaintain) { // 维护
            params.maintainImagesUrl = maintainImagesUrl[0]
              ? maintainImagesUrl[0].url
              : '';
            // 是否维保（0：否；1：是）
            params.maintenanceType = '1';
          }
          if (this.hasQuit) { // 退场
            params.exitDate = exitDate;
            // 1：入场；2：离场
            params.deviceType = '2';
          }
          if (!params.id) delete params.id;
          await this.$emit('submit', params);
        }
      });
    },
  }
};
</script>

<style scoped lang="scss">
  @import "../../../assets/styles/table";
  @import "../../../assets/styles/dialog";

  .device-add-special-comp {
    .upload-qualifications {
      .el-upload-list__item-name, .el-icon-close, .el-icon-document {
        color: #fff;
        transition: color .3s;
      }
      .el-upload-list__item:hover {
        background-color: $inputBgRbga;
        .el-upload-list__item-name, .el-icon-document, .el-icon-close {
          color: $mainColor;
        }
      }
    }
    .detail-text {
      color: $mainColor;
      .file-name {
        cursor: pointer;
        color: $mainColor;
        text-decoration: underline;
      }
    }
    .img {
      width: 120px;
      height: 120px;
    }
    .avatar-uploader-icon, .loading-container {
      display: block;
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      line-height: 120px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      &:hover {
        border-color: $mainColor;
        color: $mainColor;
      }
    }
    .img-content {
      position: relative;
    }
    .el-icon-circle-close {
      position: absolute;
      cursor: pointer;
      left: 120px;
      top: -10px;
      font-size: 30px;
      z-index: 1;
      color: #999;
      transition: color .2s;
      &:hover {
        color: $mainColor;
      }
    }
    /deep/ .el-form-item__content {
      .el-upload-list__item-name {
        color: #fff;
        &:hover {
          color: #409EFF;
        }
      }
    }
  }
</style>
